var mongoose = require('mongoose');
var User = require('../models/news-modules');

//新增数据
exports.create = function(req, res, next) {
var user = new User(req.body);
if (user.classifyID == '59cc5376b507131e4c5a2cdd') {
    user.classify = '日常';
} else if (user.classifyID == '59cc5380b507131e4c5a2cde') {
    user.classify = 'nodejs';
} else if (user.classifyID == '59cc5391b507131e4c5a2cd') {
    user.classify = 'javascript';
} else if (user.classifyID == '59cc539bb507131e4c5a2ce0') {
    user.classify = 'vscode';
} else if (user.classifyID == '59cc53b1b507131e4c5a2ce1') {
    user.classify = '科技时讯';
}
user.save()
    .then(data => {
        console.log(data);
        res.json(data);
    })
}

//修改
exports.update = function(req, res, next) {

var id = req.params.id; // req.param('id')
// 现在操作的都是mongoose而不是mongodb
User.findByIdAndUpdate(id, {
    $set: req.body
}, {
    new: false
})
    .then(data => {
        res.json({
            msg: '数据修改成功',
            status: 200
        }); // 如果你要返回数据，这个data返回的是你之前修改的那个数据内容
    })
}

//删除
exports.remove = function(req, res, next) {
var id = req.params.id; //此时id是传过来的值
console.log(req.params);
id = id.split(','); //将传递的id值变成数组遍历
console.log(typeof id);
let leng = id.length;
for (var i = 0; i < leng; i++) {
    User.findByIdAndRemove(id[i], function(err, doc) {
        if (err) {
            console.log("数据删除异常" + err);
            return;
        } else {
            res.json({
                msg: '数据删除成功',
                status: 200
            })
        }
    })
}
}

//查找
exports.list = function(req, res, next) {
var page = (req.body.page) ? req.body.page : 1;
var rows = (req.body.rows) ? req.body.rows : 10;
rows = parseInt(rows);
var queryCondition = {};
var title;
if (req.body.title && req.body.title.trim().length > 0) {
    title = req.body.title;
    queryCondition = {
        "title": new RegExp(title, 'i')
    };
}

if (req.body.classifyID && req.body.classifyID.trim().length > 0) {
    classifyID = req.body.classifyID;
    queryCondition = {
        "classifyID": classifyID
    }
}


// News.paginate(queryCondition,{page:page,limit:rows},(err,result)=>{
//     //实现动态显示条数
//     result.rows = result.docs;
//     delete result.docs;
//     res.json(result);
// })

//对查找到的数据进行分页
User.paginate(queryCondition, {
    page: page,
    limit: rows
}, function(err, result) {
    result.rows = result.docs;
    delete result.docs;
    res.json(result)
});
}

//查找想要的那个类型的所有值//
exports.listtoo = function(req, res, next) {
    // console.log(req.body._id);
var query = {
    'style[0][0]._id': req.body._id
}
User.find(query, (err, result) => {
    console.log("结果");
    console.log(result);
    res.json(result)
})
}

//查找想要指定的id
exports.listId = function(req, res, next) {
var id = (req.body.id) ? req.body.id : 1;
var query = {
    _id: id
}
User.find(query, (err, result) => {
    res.json(result)
})
}